import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:laos_mall/common/style/app_style.dart';
import 'package:laos_mall/common/style/extension_util.dart';
import 'package:laos_mall/common/widght/expansion_title_widget.dart';
import 'package:laos_mall/common/widght/mall/zb_Item_widget.dart';

enum PositionedDropdownType{
  search,
  category
}

class PositionedDropdown extends StatefulWidget {
  List<dynamic> items;
  final ValueChanged<dynamic> onItemSelected;
  final double width; // 下拉框的宽度
  final GlobalKey<PositionedDropdownState>? globalKey; // 用于外部控制
  final Widget? Function(BuildContext context, int index)? itemBuild;
  final PositionedDropdownType type;

  PositionedDropdown({
    super.key,
    required this.items,
    required this.onItemSelected,
    this.width = 200, // 默认宽度
    this.globalKey,
    this.itemBuild,
    this.type = PositionedDropdownType.search,
  });

  @override
  PositionedDropdownState createState() => PositionedDropdownState();
}

class PositionedDropdownState extends State<PositionedDropdown>
    with SingleTickerProviderStateMixin {
  OverlayEntry? _overlayEntry;
  late AnimationController _animationController;
  late Animation<double> _animation;
  List<dynamic> _items = [];

  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(
      vsync: this,
      duration: Duration(milliseconds: 300),
    );
    _animation = Tween<double>(begin: 0, end: 1).animate(
      CurvedAnimation(
        parent: _animationController,
        curve: Curves.easeInOut,
      ),
    );
    _items = widget.items;
  }


  void reloadOverlay(position, {List<dynamic>? items,bool isFirst = true}) {
    _overlayEntry?.remove();
    _overlayEntry = null;
    _items = items ?? widget.items;
    Widget child = ListView.builder(
      padding: EdgeInsets.zero,
      shrinkWrap: true,
      itemCount: _items.length,
      itemBuilder: (context, index) {
        switch (widget.type) {
          case PositionedDropdownType.search:
            return ZBItemWidget(
              style: ZBItemStyle.search,
              title: _items[index],
            ).addContainer(height: 32.h, color: Colors.transparent).addGestureTap(() {
              widget.onItemSelected(index);
              hideDropdown();
            });

          case PositionedDropdownType.category:
            return widget.itemBuild!(context, index);
        }
        return Container();
      },
    );

    _overlayEntry = OverlayEntry(
      builder: (context) => Stack(
        children: [
          if (widget.type == PositionedDropdownType.search)
            Positioned(
                left: 0,
                right: 0,
                top: position + 10.h,
                bottom: 0,
                child:
                GestureDetector(
                  onTap: () {
                    hideDropdown();
                  },
                  child: Container(
                    color: Colors.black.withOpacity(0.2),
                    width: MediaQuery.of(context).size.width,
                    height: MediaQuery.of(context).size.height,
                  ),
                ))
          else
            GestureDetector(
              onTap: () {
                hideDropdown();
              },
              child: Container(
                color: Colors.transparent,
                width: MediaQuery.of(context).size.width,
                height: MediaQuery.of(context).size.height,
              ),
            ),
          Positioned(
            left: 0,
            top: position + 10.h,
            width: widget.width,
            child: PageStorage(
              bucket: PageStorageBucket(),
              child: Material(
                color: Colors.transparent,
                child: SizeTransition(
                  sizeFactor: _animation,
                  child: Container(
                    color: Colors.white,
                    constraints: BoxConstraints(maxHeight: 400),
                    child: child,
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
    Overlay.of(context).insert(_overlayEntry!);
    if(isFirst){
      _animationController.forward();
    }
  }

  void showDropdown(position, {List<dynamic>? items}) {
    if (_overlayEntry != null){
      reloadOverlay(position,items: items,isFirst: false);
      return;
    }
    reloadOverlay(position,items: items);
  }

  void hideDropdown() {
    if (_overlayEntry == null) return;

    _animationController.reverse().then((_) {
      _overlayEntry?.remove();
      _overlayEntry = null;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(); // 不需要渲染任何内容
  }

  @override
  void dispose() {
    _animationController.dispose();
    _overlayEntry?.remove();
    _overlayEntry = null;
    super.dispose();
  }
}